﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Collections;
using System.IO;
using Microsoft.Office.Interop.Excel;
using System.Reflection;
using System.Data;

namespace OALPTool
{
    public class DataGridViewToExcel
    {
        public void OALP_DataGridViewToExcel(DataGridView dgv, ArrayList TitleList)
        {
            SaveFileDialog dialog = new SaveFileDialog();
            dialog.DefaultExt = "xls ";
            dialog.Filter = "EXCEL文件(*.XLS)|*.xls ";
            dialog.InitialDirectory = Directory.GetCurrentDirectory();
            if (dialog.ShowDialog() != DialogResult.Cancel)
            {
                string fileName = dialog.FileName;
                if (fileName.Trim() != " ")
                {
                    int count = dgv.Rows.Count;
                    int num2 = dgv.Columns.Count;
                    if (count <= 0)
                    {
                        MessageBox.Show("没有数据可供保存 ", "提示 ", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                    }
                    else if (num2 <= 0)
                    {
                        MessageBox.Show("没有数据可供保存 ", "提示 ", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                    }
                    else if (count > 0x10000)
                    {
                        MessageBox.Show("数据记录数太多(最多不能超过65536条)，不能保存 ", "提示 ", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                    }
                    else if (num2 > 0xff)
                    {
                        MessageBox.Show("数据记录行数太多，不能保存 ", "提示 ", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                    }
                    else
                    {
                        Exception exception;
                        FileInfo info = new FileInfo(fileName);
                        if (info.Exists)
                        {
                            try
                            {
                                info.Delete();
                            }
                            catch (Exception exception1)
                            {
                                exception = exception1;
                                MessageBox.Show(exception.Message, "删除失败 ", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                                return;
                            }
                        }
                        Microsoft.Office.Interop.Excel.Application application = null;
                        Workbook workbook = null;
                        Worksheet activeSheet = null;
                        try
                        {
                            Range range;
                            int num7;
                            application = new ApplicationClass();
                            workbook = application.Workbooks.Add(Missing.Value);
                            activeSheet = (Worksheet)workbook.ActiveSheet;
                            application.Visible = false;
                            int num3 = 1;
                            int num4 = 0;
                            if ((TitleList != null) && (TitleList.Count != 0))
                            {
                                num4 = TitleList.Count;
                            }
                            int num5 = 1 + num4;
                            int columnCount = dgv.ColumnCount;
                            if (num4 > 0)
                            {
                                for (num7 = 0; num7 < TitleList.Count; num7++)
                                {
                                    for (int j = 0; j < ((ArrayList)TitleList[num7]).Count; j++)
                                    {
                                        range = activeSheet.get_Range(activeSheet.Cells[Convert.ToInt32(((DataRow)((ArrayList)TitleList[num7])[j])["BegRow"]), Convert.ToInt32(((DataRow)((ArrayList)TitleList[num7])[j])["BegCol"])], activeSheet.Cells[Convert.ToInt32(((DataRow)((ArrayList)TitleList[num7])[j])["EndRow"]), Convert.ToInt32(((DataRow)((ArrayList)TitleList[num7])[j])["EndCol"])]);
                                        range.Merge(0);
                                        application.Cells[num7 + 1, Convert.ToInt32(((DataRow)((ArrayList)TitleList[num7])[j])["BegCol"])] = ((DataRow)((ArrayList)TitleList[num7])[j])["Text"].ToString();
                                        string str2 = ((DataRow)((ArrayList)TitleList[num7])[j])["Align"].ToString();
                                        if (str2.Equals("1"))
                                        {
                                            range.HorizontalAlignment = XlHAlign.xlHAlignLeft;
                                        }
                                        else if (str2.Equals("2"))
                                        {
                                            range.HorizontalAlignment = XlHAlign.xlHAlignRight;
                                        }
                                        else
                                        {
                                            range.HorizontalAlignment = XlHAlign.xlHAlignCenter;
                                        }
                                        if (num7 == 0)
                                        {
                                            range.Font.Size = 20;
                                        }
                                    }
                                }
                            }
                            for (num7 = 1; num7 <= dgv.ColumnCount; num7++)
                            {
                                if (dgv.Columns[num7 - 1].Visible)
                                {
                                    application.Cells[num4 + 1, num7] = dgv.Columns[num7 - 1].HeaderText.Trim();
                                }
                            }
                            activeSheet.get_Range(activeSheet.Cells[num4 + 1, 1], activeSheet.Cells[num4 + 1, columnCount]).Font.Bold = true;
                            for (int i = 0; i <= (dgv.RowCount - 1); i++)
                            {
                                num3 = 1;
                                for (int k = 0; k < num2; k++)
                                {
                                    if (dgv.Columns[k].Visible)
                                    {
                                        try
                                        {
                                            activeSheet.Cells[(i + num5) + 1, num3] = dgv.Rows[i].Cells[k].Value.ToString().Trim();
                                            num3++;
                                        }
                                        catch (Exception)
                                        {
                                        }
                                    }
                                }
                            }
                            activeSheet.Columns.EntireColumn.AutoFit();
                            range = activeSheet.get_Range(activeSheet.Cells[1 + num4, 1], activeSheet.Cells[num5 + dgv.RowCount, columnCount]);
                            range.Borders.LineStyle = 1;
                            range.Borders[XlBordersIndex.xlEdgeLeft].Weight = XlBorderWeight.xlThin;
                            range.Borders[XlBordersIndex.xlEdgeTop].Weight = XlBorderWeight.xlThin;
                            range.Borders[XlBordersIndex.xlEdgeRight].Weight = XlBorderWeight.xlThin;
                            range.Borders[XlBordersIndex.xlEdgeBottom].Weight = XlBorderWeight.xlThin;
                            range.WrapText = true;
                            workbook.SaveAs(fileName, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value, XlSaveAsAccessMode.xlShared, Missing.Value, Missing.Value, Missing.Value, Missing.Value, Missing.Value);
                        }
                        catch (Exception exception3)
                        {
                            exception = exception3;
                            MessageBox.Show(exception.Message, "警告 ", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
                            return;
                        }
                        finally
                        {
                            if (workbook != null)
                            {
                                workbook.Close(Missing.Value, Missing.Value, Missing.Value);
                            }
                            if (application.Workbooks != null)
                            {
                                application.Workbooks.Close();
                            }
                            if (application != null)
                            {
                                application.Quit();
                            }
                            activeSheet = null;
                            workbook = null;
                            application = null;
                        }
                        MessageBox.Show(fileName + "\n\n导出完毕! ", "提示 ", MessageBoxButtons.OK, MessageBoxIcon.Asterisk);
                    }
                }
            }
        }
    }
}
